<template>
  <div class="app-container">
    <h2>串口数据测试（免登录）</h2>
    <el-alert title="请确保已启动Electron端并连接串口" type="info" show-icon class="mb8" />
    <el-card>
      <div>最近收到的数据：</div>
      <el-input v-model="lastData" readonly type="textarea" rows="3" />
      <div class="mt8">数据历史：</div>
      <el-scrollbar height="200px">
        <div v-for="(item, idx) in dataList" :key="idx" style="font-size:13px;line-height:1.8;">{{ item }}</div>
      </el-scrollbar>
    </el-card>
    <el-card class="mt8">
      <div>串口数据发送：</div>
      <el-input v-model="sendData" placeholder="请输入要发送的数据" class="mb8" />
      <el-row :gutter="10">
        <el-col :span="12">
          <el-button type="primary" @click="handleSend">发送</el-button>
        </el-col>
        <el-col :span="12">
          <el-select v-model="interval" placeholder="定时发送间隔" style="width: 120px;">
            <el-option label="100毫秒" :value="100" />
            <el-option label="1秒" :value="1000" />
            <el-option label="2秒" :value="2000" />
            <el-option label="5秒" :value="5000" />
          </el-select>
          <el-button type="success" @click="startTimer" :disabled="timerId">开始定时</el-button>
          <el-button type="danger" @click="stopTimer" :disabled="!timerId">停止定时</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
const lastData = ref('')
const dataList = ref([])
const sendData = ref('')
const interval = ref(null)
const timerId = ref(null)

const handleSend = () => {
  if (window.electronAPI && window.electronAPI.sendSerialData && sendData.value) {
    window.electronAPI.sendSerialData(sendData.value)
  }
}

const startTimer = () => {
  if (!interval.value || !sendData.value) return
  if (timerId.value) return
  timerId.value = setInterval(() => {
    handleSend()
  }, interval.value)
}

const stopTimer = () => {
  if (timerId.value) {
    clearInterval(timerId.value)
    timerId.value = null
  }
}

onMounted(() => {
  if (window.electronAPI && window.electronAPI.onSerialData) {
    window.electronAPI.onSerialData((data) => {
      lastData.value = data
      dataList.value.unshift(`[${new Date().toLocaleTimeString()}] ` + data)
      if (dataList.value.length > 100) dataList.value.length = 100
    })
  }
})
onBeforeUnmount(() => {
  stopTimer()
})
</script> 